package com.varbal.icegame.component;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;

/**
 * 自定义拦截器
 */
public class LoginHandlerInterceptor implements HandlerInterceptor {
    Logger logger = LoggerFactory.getLogger(getClass());

//    预处理回调方法，实现处理器的预处理（如登录检查）--Controller方法处理之前
//    若返回false，则中断执行，注意：不会进入afterCompletion
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println("LoginHandlerInterceptor...preHandle...");
//        浏览器不会发送#后面的参数
        System.out.println("请求路径RequestURI："+request.getRequestURI());//request.getRequestURI()只包含路径，？传参，#后缀一概没有
        System.out.println("请求路径QueryString："+request.getQueryString());//接受？后的传参
//        return false;//不再交给controller处理，直接为空
        HttpSession session = request.getSession();
        System.out.printf("session----:");
        System.out.println(session.getId());
        try {
            if (request.getRequestURI().equals("/sss")){
                System.out.println("获取了添加tooken的请求");
                return true;
            }
            Object tooken = session.getAttribute("tooken");
            System.out.println(tooken);
            if (!tooken.equals("sssv")){
                System.out.println("tooken错误");
                return  false;
            }
        }catch (NullPointerException e){
            System.out.println("不存在tooken");
            return  false;
        }
        return true;
    }

//    后处理回调方法，实现处理器的后处理（但在渲染视图之前）Controller方法处理完之后，DispatcherServlet进行视图的渲染之前
//    链式Intercepter情况下，Intercepter按照声明的顺序倒着执行。post、get方法都能处理
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("LoginHandlerInterceptor...postHandle...");
        if(request.getRequestURI().equals("/sss")){
            HttpSession session = request.getSession();
            session.setAttribute("tooken","sssv");
            System.out.println("放入了tooken");
            System.out.println(request.getSession());
        }
    }

//    整个请求处理完毕回调方法，即在视图渲染完毕时回调，如性能监控中我们可以在此记录结束时间并输出消耗时间，还可以进行一些资源清理
//    DispatcherServlet进行视图的渲染之后   多用于清理资源
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("LoginHandlerInterceptor...afterCompletion...");
    }
}
